package com.neusoft.mapper;

import org.apache.ibatis.annotations.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Mapper
public interface CreditBillMapper {

    // 插入新账单
    @Insert("INSERT INTO wallet_bills (wallet_id, bill_amount, due_date, paid_amount, status, created_at, updated_at) " +
            "VALUES (#{walletId}, #{billAmount}, #{dueDate}, 0, '未还', NOW(), NOW())")
    void insertNewBill(@Param("walletId") Long walletId,
                       @Param("billAmount") BigDecimal billAmount,
                       @Param("dueDate") Date dueDate);

    // 获取总的未偿还金额
    @Select("SELECT COALESCE(SUM(bill_amount - paid_amount), 0) FROM wallet_bills WHERE wallet_id = #{walletId} AND status = '未还'")
    BigDecimal findOutstandingBill(@Param("walletId") Long walletId);

    // 部分还款更新账单
    @Update("UPDATE wallet_bills SET paid_amount = paid_amount + #{paymentAmount}, updated_at = NOW() " +
            "WHERE wallet_id = #{walletId} AND status = '未还' AND (bill_amount - paid_amount) >= #{paymentAmount}")
    void updateBillPartialPayment(@Param("walletId") Long walletId, @Param("paymentAmount") BigDecimal paymentAmount);

    // 将账单标记为已还清
    @Update("UPDATE wallet_bills SET status = '已还清', updated_at = NOW() " +
            "WHERE wallet_id = #{walletId} AND status = '未还' AND (bill_amount - paid_amount) <= 0")
    void markBillAsPaid(@Param("walletId") Long walletId);

    @Select("SELECT due_date FROM wallet_bills WHERE wallet_id = #{walletId} AND status = '未还'")
    Date findBillDueDate(@Param("walletId") Long walletId);

    @Select("SELECT bill_amount - paid_amount FROM wallet_bills WHERE wallet_id = #{walletId} AND status = '未还'")
    List<BigDecimal> findOutstandingBills(@Param("walletId") Long walletId);
}
